package com.momo.seckilling.EventModel;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by li on 2019/3/18.
 */
public class OrderEventProcessor implements Handle{
    private CentralEventProcessor centralEventProcessor;
    private StateMachine stateMachine = new StateMachine();
    public OrderEventProcessor(CentralEventProcessor centralEventProcessor){
        this.centralEventProcessor = centralEventProcessor;
    }

    @Override
    public void handle(Event event) {
        try {
            OrderEvent orderEvent = (OrderEvent)event;
            StateProcess stateProcess = this.stateMachine.getProcessBySateType(orderEvent);
            stateProcess.process(orderEvent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class StateMachine {
        private Map<OrderEventType,StateProcess> processColletion = new HashMap<OrderEventType,StateProcess>();
        public StateMachine(){
            processColletion.put(OrderEventType.NEW,new NewStateProcess());
            processColletion.put(OrderEventType.COMPLETE,new CompleteStateProcess());
            processColletion.put(OrderEventType.FAIL,new FailStateProcess());
        }
        public StateProcess getProcessBySateType(OrderEvent orderEvent){
            OrderEventType orderEventType = orderEvent.getOrderEventType();
            StateProcess stateProcess = processColletion.get(orderEventType);
            return stateProcess;
        }
    }

    public class NewStateProcess implements StateProcess {
        public void process(Event event){
            System.out.println("订单开始创建");
            Event orderComplete = new OrderEvent("complete",OrderEventType.COMPLETE);
            try {
                centralEventProcessor.centralQueue.put(orderComplete);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public class CompleteStateProcess implements StateProcess {
        public void process(Event event){
            System.out.println("订单创建完毕");
        }
    }

    public class FailStateProcess implements StateProcess {
        public void process(Event event){

        }
    }

}
